//
//  BasicEventWebView.m
//  MIS Cloud
//
//  Created by goldeney on 14-1-22.
//  Copyright (c) 2014年 goldeneye. All rights reserved.
//

#import "AbstractWebLoadAnimationView.h"
#import "AbstractBaseWebView.h"

#import "AESCrypt.h"
#import "WebGetUserInfoToHttp.h"

@interface AbstractWebLoadAnimationView()

@property (nonatomic, strong) AbstractBaseWebView *webView;
@property (nonatomic, strong) TYMActivityIndicatorView *activityIndicatorView;
@property (nonatomic, strong) NSMutableURLRequest *request;

@property (nonatomic, assign) BOOL isLoadingFinish;

@end

@implementation AbstractWebLoadAnimationView
@synthesize webView = _webView;
@synthesize activityIndicatorView = _activityIndicatorView;
@synthesize request = _request;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        CGRect bounds = frame;
        [self initWebViewWithFrame:bounds];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        // Initialization code
        CGRect bounds = self.bounds;
        [self initWebViewWithFrame:bounds];
    }
    return self;
}

- (void)dealloc
{
    self.webView.delegate = nil;
    self.webView = nil;
    self.activityIndicatorView = nil;
    self.request = nil;
}

- (void)initWebViewWithFrame:(CGRect)frame
{
    self.backgroundColor = [UIColor colorWithWhite:0.95f alpha:1.0f];
    
    //创建网页显示页面
    if(!_webView){
        _webView = [[AbstractBaseWebView alloc] initWithFrame:frame];
        self.webView.delegate = self;
//        self.webView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
        self.webView.scalesPageToFit = YES;
        _webView.scrollView.bounces = NO;
        _webView.userInteractionEnabled = NO;
        [self addSubview:_webView];
    }
    
    //创建进度条
    if (!self.activityIndicatorView) {
        CGSize size = self.bounds.size;
        CGFloat offsetX = size.width/2 - 107.0f/2;
        CGFloat offsetY = size.height/2 - 107.0f/2 + 23;
        
        self.activityIndicatorView = [[TYMActivityIndicatorView alloc] initWithActivityIndicatorStyle:TYMActivityIndicatorViewStyleLarge];
        _activityIndicatorView.hidesWhenStopped = YES;
        _activityIndicatorView.frame = CGRectMake(offsetX, offsetY, 107.0f, 107.0f);
        _activityIndicatorView.delegate = self;
        _activityIndicatorView.userInteractionEnabled = YES;
        [self addSubview:_activityIndicatorView];
    }
    
}

- (void)reload
{
    //判断是否在加载数据
    if (!_webView.isLoading) {
        NSURLRequest *urlRequest = _webView.request;
        NSString *url = urlRequest.URL.absoluteString ;
        if (!(url && ![url isEqualToString:@""])) urlRequest = self.request;
        [_webView stopLoading];
        
        [_webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML='';"];
        [_webView loadRequest:urlRequest];
    }
    
}

- (void)loadRequest:(NSURLRequest *)request
{
    [_webView loadRequest:request];
}

- (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL
{
    [_webView loadHTMLString:string baseURL:baseURL];
}

- (void)loadRequestURLString:(NSString *)URLString parasData:(NSDictionary*)requestData
{
    //URL中文字符及特殊字符处理
    NSString *requestString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes
    (kCFAllocatorDefault,(CFStringRef)URLString,NULL,NULL,kCFStringEncodingUTF8));
    
    //数据生成处理
    NSURL *url = [NSURL URLWithString:requestString];
    self.request = [[NSMutableURLRequest alloc] initWithURL:url];
    NSMutableString *body = [[NSMutableString alloc] initWithCapacity:0];
    
    //遍历数据，获取到参数
    if (requestData && [requestData isKindOfClass:[NSDictionary class]] && requestData.count>0) {
        
        NSArray *keys = [requestData allKeys];// 所有key
        for(int i=0;i<[keys count];i++){
            NSString *key = [keys objectAtIndex:i];
            NSString *encodeValue = [requestData objectForKey:key];
            
            //URL中文字符及特殊字符处理
            NSString *requestString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes
            (kCFAllocatorDefault,(CFStringRef)encodeValue,NULL,CFSTR("!*'();:@&=+$,/?%#[]"),kCFStringEncodingUTF8));
            
            //NSLog(@"Key:%@ == Value:%@",key,requestString);
            [body appendFormat:@"%@=%@&",key,requestString];
        }
        
    }
    
    //传递用户信息
    NSString *replacString = [WebGetUserInfoToHttp getUserInfoToJSON];
    [body appendFormat:@"session=%@&",replacString];
    
    //删除多余的“&”字符
    if(body.length>0) [body deleteCharactersInRange:NSMakeRange(body.length - 1, 1)];
    
    //以POST方式发起数据连接
    [_request setHTTPMethod:@"POST"];
    [_request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
    
    //开始请求数据
    [_webView loadRequest:_request];
}

//字典转Json
- (NSString*)dictionaryToJson:(NSDictionary *)dic
{
    NSError *parseError = nil;
    NSData  *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}


- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script
{
    return [_webView stringByEvaluatingJavaScriptFromString:script];
}

#pragma mark -
#pragma mark TYMActivityIndicatorViewDelegate

- (void)refreshSelector:(id)button
{
    self.activityIndicatorView.hidden = NO;
    [self.activityIndicatorView startAnimating];
    [self loadRequest:_request];
}


#pragma mark -
#pragma mark UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    _webView.userInteractionEnabled = NO;
    if (!self.activityIndicatorView.isAnimating) {
        self.activityIndicatorView.hidden = NO;
        [self.activityIndicatorView startAnimating];
    }
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    _webView.userInteractionEnabled = YES;
    if (self.activityIndicatorView.isAnimating) {
        self.activityIndicatorView.hidden = YES;
        [self.activityIndicatorView stopAnimating];
    }
    
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    NSLog(@"===didFailLoadWithError===%@",error);
    _webView.userInteractionEnabled = NO;
    [self.activityIndicatorView showErrorView];
}

@end
